using System;
using System.Collections.Generic;

namespace Bordecal.ImportsSorter
{
	/// <summary>
	/// Comparer for sorting strings in descending order by string length.
	/// </summary>
	internal sealed class DescendingStringLengthComparer : IComparer<string>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the DescendingStringLengthComparer class.
		/// </summary>
		internal DescendingStringLengthComparer()
		{
		}

		#endregion

		#region IComparer<string> Members

		/// <summary>
		/// Compares two strings according to their length.
		/// </summary>
		/// <remarks>
		/// If both strings are equal in length, the result of a case-insensitive
		/// string comparison is returned.
		/// </remarks>
		/// <param name="x">The first object to compare.</param>
		/// <param name="y">The second object to compare.</param>
		/// <returns>
		///		<list type="table">
		///			<listheader>
		///				<term>Value</term>
		///				<description>Condition</description>
		///			</listheader>
		///			<item>
		///				<term>Less than zero</term>
		///				<description>The first string is longer than the second string.</description>
		///			</item>
		///			<item>
		///				<term>Zero</term>
		///				<description>The strings are equal.</description>
		///			</item>
		///			<item>
		///				<term>Greater than zero</term>
		///				<description>The first string is shorter than the second string.</description>
		///			</item>
		///		</list>
		/// </returns>
		public int Compare(string x, string y)
		{
			int retVal;

			if (object.ReferenceEquals(x, y))
			{
				retVal = 0;
			}
			else if (x == null)
			{
				retVal = 1;
			}
			else if (y == null)
			{
				retVal = -1;
			}
			else
			{
				retVal = Comparer<int>.Default.Compare(y.Length, x.Length);
				if (retVal == 0)
				{
					retVal = StringComparer.OrdinalIgnoreCase.Compare(x, y);
				}
			}

			return retVal;
		}

		#endregion
	}
}